import { HealthCheckWithScreenTask, V3proLastErrCache } from "./health.check.class";
import { SendboxKey, V3proSubjectMessage } from "../model/v3pro.model";
import { V3proScreen, V3proScreenAllStatus } from "../../../api/v3pro-api/v3pro.api.response.model";
import { V3proScreenLayoutHelper } from "../helper/v3pro.screen.layout.helper";
import { V3proAlertMessageErrTypeEnum } from "../model/v3pro.enum";
import { V3proAllStatusLambda } from "../helper/v3pro.all.status.lambda.helper";
import { appConfig } from "../../../configs/env.config.load";
import { V3proFileHelper } from "../helper/v3pro.file.helper";

/**
 * 扫描板电压异常
 *
 * 是否支持阈值设置： N
 *
 * 查询周期:
 * 由扫描板主动上报
 *
 * 告警产生的原因:
 * 扫描板电压超出正常工作范围
 *
 * 异常现象:
 * 机箱显示花屏
 *
 * 维修建议:
 * 依次排查电源、转接板、扫描板等硬件
 *
 * 告警级别: 次要
 */
const errCache = new V3proLastErrCache<SendboxKey>();
export class V3proCheckSendboxDoorTask extends HealthCheckWithScreenTask<SendboxKey[]> {
  async checkResult(
    keyParams: SendboxKey[],
    screenId: string,
    allStatus: V3proScreenAllStatus,
    screenLayoutHelper: V3proScreenLayoutHelper,
  ) {
    const message = new V3proSubjectMessage();
    if (keyParams.length === 0) return message;
    message.setErrStatus();
    keyParams.forEach((box) => screenLayoutHelper.setSendBoxErrById(box.id), 2);
    message.files = [await V3proFileHelper.sendBoxKey2File(keyParams)];
    return message;
  }

  async genKeyParams(
    allStatus: V3proScreenAllStatus,
    screen: V3proScreen,
    screenLayoutHelper: V3proScreenLayoutHelper,
  ): Promise<SendboxKey[]> {
    const openStatus = appConfig.v3pro.errEnable.doorOpenIsOnStatus ? "on" : "off";
    const [errs, normals] = V3proAllStatusLambda.filterSendBoxesWithRemove(allStatus, (sendBox) => {
      return sendBox.status?.ioInputArr?.[0]?.status === openStatus;
    });
    return errCache.mergeCache(
      errs.map(SendboxKey.build),
      normals.map(SendboxKey.build),
      screen.id,
      (s) => s.id,
    );
  }

  genSRMqttTopic(
    message: V3proSubjectMessage,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): string {
    return `notify/alert/ssads/device-sensor:door-open-alert/${screenId}`;
  }

  getV3proAlertMessage(): V3proAlertMessageErrTypeEnum {
    return V3proAlertMessageErrTypeEnum.DOOR_OPEN;
  }

  isNeedUploadFile(
    message: V3proSubjectMessage,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): boolean {
    return message.isErrStatus();
  }

  isReportEnabled(keyParams: SendboxKey[], screenId: string): boolean {
    return appConfig.v3pro.errEnable.doorOpenAlert;
  }
}
